﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThermalMarker.Entities;
using ThermalMarker.Utils;
using System.IO;

namespace ThermalMarker
{
    public partial class ThermalMarker : Form
    {
        private OpenFileDialog origFilesDialog;
        private List<WayPoint> processedWPTs = new List<WayPoint>();
        private double maxThermalDistance = 0;
        private string[] fileList;

        public int tempArrayNumber = 1;

        public ThermalMarker()
        {
            InitializeComponent();
        }

        private void btnSearchFiles_Click(object sender, EventArgs e)
        {
            origFilesDialog = new OpenFileDialog();
            origFilesDialog.Multiselect = true;

            if (origFilesDialog.ShowDialog() == DialogResult.OK)
            {
                if (origFilesDialog.FileNames.Count() > 0)
                {
                    txtOrigFiles.Lines = origFilesDialog.FileNames;
                    fileList = origFilesDialog.FileNames;

                }

            }
        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            maxThermalDistance = Double.Parse(txtTermalDistance.Text);
            
            tempArrayNumber = 1;
            processedWPTs.Clear();


            foreach (string file in fileList)
            {
                try
                {
                    string[] fileLines = File.ReadAllLines(file);

                    ProcessFileLines(fileLines);
                }
                catch (Exception ex)
                { }
            }

            GenerateWPTFile();


        }

        private void GenerateWPTFile()
        {
            int numberFiles = fileList.Count();

            decimal value = (decimal)tbrDetail.Value * numberFiles / tbrDetail.Maximum;

            decimal roundValue = Math.Round(value);

            GenerateFile(roundValue);
        }

        private void GenerateFile(decimal roundValue)
        {
            string dirPath = Path.GetDirectoryName(fileList[0]);

            string filePath = dirPath + "\\Output_" +DateTime.Now.TimeOfDay.TotalSeconds.ToString() + ".wpt";

            try
            {
                FileStream outputFile = File.Open(filePath, FileMode.CreateNew);

                StreamWriter writer = new StreamWriter(outputFile);

                writer.WriteLine("OziExplorer Waypoint File Version 1.1");
                writer.WriteLine("WGS 84");
                writer.WriteLine("Reserved 2");
                writer.WriteLine("garmin16");

                foreach (WayPoint wpt in processedWPTs)
                {
                    if (wpt._relatedPoints.Count == roundValue - 1 && roundValue > 1)
                    {
                        writer.Write(wpt.ArrayNumber);
                        writer.WriteLine(wpt.FileLine.Remove(0,4));
                    }
                        
                    else
                        if (roundValue <= 1)
                        {
                            writer.Write(wpt.ArrayNumber);
                            writer.WriteLine(wpt.FileLine.Remove(0, 4));
                        }

                }


                writer.Flush();
                writer.Close();
                outputFile.Close();

            }
            catch (Exception ex)
            { }
            
        }

        private void ProcessFileLines(string[] fileLines)
        {
            List<WayPoint> waypoints = new List<WayPoint>();

            foreach (string line in fileLines)
            {
                WayPoint wpt = new WayPoint(line);

                if (wpt != null)
                {
                    waypoints.Add(wpt);
                }
                

                string[] lineArray = line.Split(',');

                if (lineArray.Count() == 19)
                {
                    bool found = false;

                    double latitude = double.Parse(lineArray[2]) / 1000000;
                    double longitude = double.Parse(lineArray[3]) / 1000000; 
                  
                    WayPoint current = new WayPoint(latitude,longitude,line,tempArrayNumber);

                    foreach (WayPoint wpt in processedWPTs)
                    {
                        if (MathFunctions.DistanceBetweenWPS(wpt, current) * 1000 <= maxThermalDistance)
                        {
                            wpt._relatedPoints.Add(current);
                            tempArrayNumber++;
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        processedWPTs.Add(current);
                        tempArrayNumber++;
                    }

                }
            }
        }

    }
}
